/*
 * @Author: Quinn
 * @Date: 2023-03-03 15:23:09
 * @LastEditors: quinn
 * @Description:
 */
import axios from "axios";
import { query2string, jsonToForm, jsonToXXX } from "@/utils/index";
import { Message ,Notification} from "element-ui";
import { LOGIN_PATH } from "@/assets/js/define";
import Vue from 'vue';
let loadingIns = null;
let timer = null;
const timeout = 60000;

const instance = axios.create({
  timeout,
});

const onLoadingConfig = (config) => {
  const { loadingConfig = {}, loadingType = "" } = config;
  return {
    ...loadingConfig,
  };
};

const responseSuccess = async (response) => {
  const { config = {}, data: res = {} } = response;
  const { silence, fit, ignore } = config;
  if (ignore) return Promise.resolve(res);

  if ([200].includes(res?.code)) {
    if(config.url.indexOf('new/cad/parse') > -1){

      if(Array.isArray(res.result.code) && res.result.code.length >0){
        Notification.error({
          title: '转化图解析错误:',
          duration: 0,
          offset:100,
          message:`错误编码:${res.result.code}
           `
        })
      }
      if(Array.isArray(res.result.code2) && res.result.code2.length >0){
        Notification.error({
          title: '仓储图解析错误:',
          duration: 0,
          offset:150,
          message:` 
                错误编码:${res.result.code2}
           `
        })
      }
      if(Array.isArray(res.result.code3) && res.result.code3.length >0){
        Notification.error({
          title: '仓储报价图解析错误:',
          duration: 0,
          offset:300,
          message:`
              错误编码:${res.result.code3}
           `
        })
      }
      if(Array.isArray(res.result.code4) && res.result.code4.length >0){
        Notification.error({
          title: '营业区报价图解析错误:',
          duration: 0,
          offset:450,
          message:` 
                错误编码:${res.result.code4}
           `
        })
      }
    return;
    }
    if (typeof fit === "function") return Promise.resolve(fit(res?.result));
    return Promise.resolve(res?.result);
  } else if ([10043, 10042].includes(res?.code)) {
    window.location.href = LOGIN_PATH;
    return Promise.reject(res);
  } else {
    if (!silence) Message.warning(res?.msg || "发生了一些小问题~");
    return Promise.reject(res);
  }
};

const responseFail = async (error) => {
  console.log(error);
  const { response = {}, config = {}, data: res = {} } = error;
  if (axios.isAxiosError(error))
    Message.warning(response?.data?.message || `网络错误，请稍后重试！`);
  const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  if (reg.test(error))
    Message.warning(response?.data?.message || `请稍后重试！`);
  return Promise.reject(error?.response?.status === 500 ? response : error);
};

const requestSuccess = (config) => {
  try {
    const { loading = "加载中..." } = config;
    if (loading) {
    }
  } catch (e) {
    console.log(e);
  }
  return config;
};

instance.interceptors.request.use(requestSuccess, (error) => {
  return Promise.reject(error);
});

instance.interceptors.response.use(responseSuccess, responseFail);

export async function post(url, data = {}, config = {}) {
  let { headers = {} } = config;
  return instance.post(url, data, {
    ...config,
    headers,
  });
}

export async function postForm(url, data = {}, config = {}) {
  const form = jsonToForm(data);
  console.log(form)
  return instance.post(url, form, {
    ...config,
    headers: {
      ...(config.headers || {}),
      
      "Content-Type": `multipart/form-data; boundary=${form._boundary}`,
    },
  });
}

export async function postForm2(url, data = {}, config = {}) {
  // const params = jsonToXXX(data);
  const params = data
  return instance.post(url, params, {
    ...config,
    headers: {
      ...(config.headers || {}),
      //  "Content-Type": "application/x-www-form-urlencoded",
       "Content-Type": "application/json",
    },
  });
}

export async function get(url, data = {}, config = {}) {
  if (data && Object.keys(data).length > 0) {
    url += "?" + query2string(data);
  }
  return instance.get(url, config);
}

export async function deleteFn(url, data = {}, config = {}) {
  if (data && Object.keys(data).length > 0) {
    url += "?" + query2string(data);
  }
  return instance.delete(url, config);
}

export async function patch(url, data = {}, config = {}) {
  return instance.patch(url, data, config);
}

export default { post, postForm, postForm2, get, patch, deleteFn };
